layui.use(['form', 'layer', 'table', 'treeTable'], function () {

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;

    var treeTable = layui.treeTable;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var sorting_url = $('.sorting_url').val();

    var icons_url = $('.icons_url').val();


    if ($('#dataTable').length > 0) {
        // Table 列表
        var tableIns = treeTable.render({
            elem: '#dataTable',
            url: datalist_url,
            cellMinWidth: 95,
            //height : "full-100",
            id: "tableList",
            /*reqData: function (data, callback) {
                // 在这里写ajax请求，通过callback方法回调数据
                $.get(datalist_url, function (res) {
                    if (res.code == 0) {
                        callback(res.data);
                    } else {
                        callback(res.msg);
                    }
                });
            },*/
            tree: {
                iconIndex: 1, // 折叠图标显示在第几列
                isPidData: true, // 是否是id、pid形式数据
                idName: 'id', // id字段名称
                pidName: 'parent_id', // pid字段名称
                onlyIconControl: false, // 仅允许点击图标折叠
                arrowType: 'arrow2', // arrowType
                getIcon: function(obj) {  // 自定义图标
                    // obj 是当前行的数据
                    if (obj.parent_id == 0) {  // 判断是否有子集
                        return '<i class="ew-tree-icon ew-tree-icon-folder"></i>';
                    } else {
                        return '<i class="ew-tree-icon ew-tree-icon-file"></i>';
                    }
                }
            },
            cols: [[
                /*{field: 'id', title: '序号', width: 80, align: "center"},*/
                {field: 'id', title: '序号', align: "center"},
                {field: 'name', title: '名称', minWidth: 180, align: "left"},
                {
                    field: 'url', title: 'URL', minWidth: 200, align: "center", templet: function (data) {
                        return data.app + data.controller + data.action;
                    }
                },
                {
                    field: 'status', title: '图标', align: "center", templet: function (data) {
                        if (data.icon) {
                            return '<i class="layui-icon ' + data.icon + '"></i>';
                        }
                    }
                },
                {
                    field: 'status', title: '状态', align: "center", templet: function (data) {
                        if (data.status == 1) {
                            return '<button type="button" class="layui-btn layui-btn-normal layui-btn-xs">显示</button>';
                        } else if (data.status == 2) {
                            return '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs">隐藏</button>';
                        } else {
                            return '<button type="button" class="layui-btn layui-btn-danger layui-btn-xs">删除</button>';
                        }
                    }
                },
                {field: 'created_at', title: '添加时间', minWidth: 160, align: "center"},
                {
                    title: '操作', fixed: "right", align: "center", minWidth: 160, templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                        return html;
                    }
                }
            ]],
            done: function (res, curr, count) {
                fixColumn();
            }
        });

        //固定列
        function fixColumn() {
            // thead
            $.each($('thead tr'), function (index, item) {
                $(item).find('th').last().css({
                    'border-left': '1px solid #e6e6e6 !important',
                    'position': '-webkit-sticky',
                    'position': 'sticky',
                    'right': '0',
                    'background': '#fafafa',
                    'z-index': '999'
                });
            });
            // tbody
            $.each($('tbody tr'), function (index, item) {
                $(item).find('td').last().css({
                    'border-left': '1px solid #e6e6e6 !important',
                    'position': '-webkit-sticky',
                    'position': 'sticky',
                    'right': '0',
                    'background': 'white',
                    'z-index': '999'
                });
            });
        }

        // 搜索
        $(".search_btn").on("click", function () {
            var name = $('.searchBox').find('input[name=name]').val();
            if (name != '') {
                treeTable.reload("tableList", {
                    where: {
                        name: name,
                    }
                });
            } else {
                layer.msg("请选择筛选条件");
            }
        });

        // 清空搜索
        $(".reset_btn").on("click", function () {
            treeTable.reload("tableList", {
                where: {}
            });
        });

        // 列表操作
        treeTable.on('tool(dataTable)', function (obj) {
            var layEvent = obj.event,
                data = obj.data;
            // 删除
            if (layEvent === 'del') {
                layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
                    /*$.ajax({
                        url: delete_url,
                        data: {"id": data.id},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                layer.msg('已删除', {icon: 1, time: 1000});
                                tableIns.reload();
                                layer.close(index);
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });*/
                });
            } else if (layEvent === 'edit') {
                //formHtml(data);
                var url = edit_url + '?id=' + data.id;
                formHtml(url);
            }
        });

        // 展开/收缩
        $(document).on('click', '.open-btn', function () {
            var _this = $(this);
            if (_this.attr('data-type') == 'up') {
                _this.html('<i class="layui-icon layui-icon-down layuiadmin-button-btn"></i>展开');
                _this.attr('data-type', 'down');
                tableIns.foldAll();  // 折叠全部
            } else {
                _this.html('<i class="layui-icon layui-icon-up layuiadmin-button-btn"></i>收缩');
                _this.attr('data-type', 'up');
                tableIns.expandAll();  // 展开全部
            }
        });
    }

    $('.addChild_btn').on('click', function () {
        var url = add_url + '?parent_id=' + $(this).attr('data-id');
        formHtml(url);
    });
    $('.add_btn').on('click', function () {
        formHtml(add_url);
    });
    $('.edit_btn').on('click', function () {
        //var data = {};
        var url = edit_url + '?id=' + $(this).attr('data-id');
        formHtml(url);
    });
    $('.del_btn').on('click', function () {
        var data = {};
        data.id = $(this).attr('data-id');
        layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
            $.ajax({
                url: delete_url,
                data: {"id": data.id},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('已删除', {icon: 1, time: 1000});
                        layer.close(index);
                        window.location.reload();
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        });
    });
    // 排序
    $('.sorting').on('blur', function () {
        var id = $(this).prev('.sorting_ids').val();
        var sorting = $(this).val();
        var sorting_ids = [id];
        var sorting = [sorting];
        var data = {
            'sorting_ids': sorting_ids,
            'sorting': sorting
        };
        console.log(data);

        $.ajax({
            url: sorting_url,
            data: data,
            type: "POST",
            dataType: "json",
            success: function (res) {
                layer.msg(res.msg);
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    });

    // Form 表单
    function formHtml(url) {
        var content = url;

        var index = layer.open({
            title: "后台菜单管理",
            type: 2,
            area: ["600px", "600px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    }

    // 选择图标
    $('.select-icon').on('click', function () {
        var content = icons_url;

        var index = layer.open({
            title: "图标管理",
            type: 2,
            area: ["800px", "600px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    });
    // 删除图标
    $('.del-icon').on('click', function () {
        $('.icon_name').val('');
        $('.icon_design').find('i').removeClass();
    });
    $('.icon_name').on('change', function () {
        $('.icon_design').find('i').removeClass();
    });

    // 表单提交
    form.on("submit(laySave)", function (data) {
        submitForm(data);
    });

    // 表单提交
    function submitForm(data) {
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function (res) {
                layer.msg(res.msg);
                if (res.code == 1) {
                    layer.closeAll("iframe");
                    parent.location.reload();
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    }
});
